import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_alibc/alibc_const_key.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_yres/tool/DateUtils.dart';
import 'package:flutter_yres/main.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:xlive_switch/xlive_switch.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import '../user/BindZfb.dart';
import './login_pwd_page.dart';
import './chage_phone_page.dart';
import './SetPayPwd.dart';
import '../login/BindWx.dart';
import 'package:fake_wechat/fake_wechat.dart';
import 'package:flutter_yres/tool/Toast.dart';
import './BindReferrer.dart';
import './ReferrerMsg.dart';
import './ArticleDetail.dart';

class SystemPage extends StatefulWidget {
//  @override
//  Widget build(BuildContext context) {
//    // TODO: implement build
//    ;
//    return new SystemView();
//  }

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new SystemView();
  }
}

class SystemView extends State<SystemPage> {
  bool check = false;
  String _cacheSizeStr = "0.00", account = "";
  String token = "", packageName = "1.0.0";
  String phone = "",
      nickname = "",
      avatar = "",
      truename,
      birthday,
      yaoqin,
      auth_code = '';
  int sex = 1;
  bool isBind = false;

  bool isLogin = false, isWxInstall = true, showPhone = true, isBind_tb = false;
  Wechat _wechat = Wechat()
    ..registerApp(
      appId: WX_APPID,
      universalLink: WECHAT_UNIVERSAL_LINK,
    );
  StreamSubscription<WechatAuthResp> _auth;
  WechatAuthResp _authResp;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkWx();
    _auth = _wechat.authResp().listen(_listenAuth);

    loadCache();
    getString(TOKEN).then((value) {
      token = value;
      print(token);
      is_bindTJ();
      isBindTb();
    });
    getBoolean(INFORM).then((value) {
      if (value == null) {
      } else {
        check = value;
        setState(() {});
      }
    });
    if (APPLIC.userInfoMap != null) {
      print(APPLIC.userInfoMap);
      auth_code = APPLIC.userInfoMap['user_msg']['auth_code'].toString();
      account = APPLIC.userInfoMap['user_detail']['alipay_account'].toString();
      phone = APPLIC.userInfoMap['user_msg']['phone'].toString();
      nickname = APPLIC.userInfoMap['user_detail']['nickname'] == null
          ? "未设置"
          : APPLIC.userInfoMap['user_detail']['nickname'].toString();
      sex = APPLIC.userInfoMap['user_detail']['sex'] == null
          ? 3
          : int.parse(APPLIC.userInfoMap['user_detail']['sex']);
      truename = APPLIC.userInfoMap['user_detail']['truename'].toString();
      avatar = APPLIC.userInfoMap['user_detail']['avatar'];
      isBind = (APPLIC.userInfoMap['user_msg']['openid'] != null &&
          APPLIC.userInfoMap['user_msg']['openid'].toString().length > 5);
      birthday = APPLIC.userInfoMap['user_detail']['birthday'].toString();

      setState(() {});
    }
  }

  bintTb(String uid) async {
    //获取推荐人信息
    Map map = new Map();
    uid=uid.substring(uid.length-6);
    map['token'] = token;
    List<String> lists=uid.split("");
    map['tb_uid']=lists[0]+lists[1]+lists[4]+lists[5]+lists[2]+lists[3];
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.BindingTaobaoUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Toast.toast(context,msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        isBind_tb=true;
      });
    } else {
    }
  }

  isBindTb() async {
    //获取推荐人信息
    Map map = new Map();
    map['token'] = token;
    // map['sign_type'] = SignType.FREEZE_ACCOUNT;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.WhetherBindingTaobaoUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(userMap);
    if (code == 1 && mounted) {
      setState(() {
        isBind_tb = userMap['data']['is_binding'] == "Y";
      });
    } else {}
  }

  void _getUserMsg(token) async {
    FormData data = new FormData.fromMap({'token': token});
    print(token);
    Response<String> response =
        await HttpUtil().post(Api.GetUserMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    print('获取用户信息');
    print(userMap);
    if (userMap['code'] == 1) {
      if (mounted) {
        setState(() {
          APPLIC.userInfoMap = userMap['data'];
          account =
              APPLIC.userInfoMap['user_detail']['alipay_account'].toString();
          phone = APPLIC.userInfoMap['user_msg']['phone'].toString();
          nickname = APPLIC.userInfoMap['user_detail']['nickname'] == null
              ? "未设置"
              : APPLIC.userInfoMap['user_detail']['nickname'].toString();
          sex = int.parse(APPLIC.userInfoMap['user_detail']['sex']);
          truename = APPLIC.userInfoMap['user_detail']['truename'].toString();
          avatar = APPLIC.userInfoMap['user_detail']['avatar'];
          isBind = (APPLIC.userInfoMap['user_msg']['openid'] != null &&
              APPLIC.userInfoMap['user_msg']['openid'].toString().length > 5);
          birthday = APPLIC.userInfoMap['user_detail']['birthday'].toString();
        });
      }
    }
  }

  checkInform() async {
    if (check == true) {
      setState(() {
        check = false;
        saveBoolean(INFORM, check);
      });
      return;
    } else {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.notification);
      if (permission.value == PermissionStatus.granted.value) {
        setState(() {
          check = true;
          saveBoolean(INFORM, check);
        });
        return;
      }
    }
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler()
            .requestPermissions([PermissionGroup.notification]);
    if (permissions[PermissionGroup.notification].value ==
        PermissionStatus.granted.value) {
      setState(() {
        check = true;
        saveBoolean(INFORM, check);
      });
    } else {
      if (Platform.isIOS) {
        bool isOpened = await PermissionHandler().openAppSettings();
        print(isOpened);
        if (isOpened) {
          checkInformPermission();
        }
      } else {
        bool isShown = await PermissionHandler()
            .shouldShowRequestPermissionRationale(PermissionGroup.notification);
        if (!isShown) {
          bool isOpened = await PermissionHandler().openAppSettings();
          if (isOpened) {
            checkInformPermission();
          }
        }
      }
    }
  }

  checkInformPermission() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.notification);
    if (permission.value == PermissionStatus.granted.value) {
      setState(() {
        check = true;
        saveBoolean(INFORM, check);
      });
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
      appBar: new AppBar(
        title: new Text(
          "我的资料",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: SingleChildScrollView(
          child: new Container(
        width: window.physicalSize.width,
        // height: window.physicalSize.height,
        color: divideColor,
        child: new Column(
          children: <Widget>[
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(DP_10), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  selHead();
                  // Navigator.of(context)
                  //     .push(MaterialPageRoute(builder: (context) {
                  //   return new ChangePhonePage();
                  // }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '头像',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    ClipOval(
                      child: avatar == null || avatar == ""
                          ? Image.asset("images/pic_default.png",
                              fit: BoxFit.cover,
                              width: ScreenUtil.getInstance().setHeight(DP_60),
                              height: ScreenUtil.getInstance().setHeight(DP_60))
                          : Image.network(avatar,
                              fit: BoxFit.cover,
                              width: ScreenUtil.getInstance().setHeight(DP_60),
                              height:
                                  ScreenUtil.getInstance().setHeight(DP_60)),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            // Container(
            //   padding:
            //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            //   margin: EdgeInsets.fromLTRB(
            //       0, ScreenUtil.getInstance().setHeight(1), 0, 0),
            //   color: Colors.white,
            //   child: new GestureDetector(
            //     onTap: () {
            //       Navigator.of(context)
            //           .push(MaterialPageRoute(builder: (context) {
            //         return new IdentityPage();
            //       }));
            //     },
            //     child: new Row(
            //       children: <Widget>[
            //         Expanded(
            //           child: Text(
            //             '实名认证',
            //             style: TextStyle(
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(NORMAL_FONT_SIZE),
            //                 color: Colors.black87),
            //           ),
            //         ),
            //         Text(truename == null ? "未认证" : "已认证",
            //             style: TextStyle(
            //                 color: Colors.grey,
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(SMALL_FONT_SIZE))),
            //         Icon(
            //           Icons.arrow_forward_ios,
            //           color: Colors.grey,
            //           size: 20,
            //         )
            //       ],
            //     ),
            //   ),
            // ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return new ChangePhonePage();
                  }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '个人账号',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(phone,
                        style: TextStyle(
                            color: Colors.grey,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  showCupertinoDialog(
                      context: context,
                      builder: (context) {
                        return CupertinoAlertDialog(
                          title: Text('请输入昵称'),
                          content: Card(
                            elevation: 0.0,
                            child: Column(
                              children: <Widget>[
                                TextField(
                                  onChanged: (value) {
                                    nickname = value;
                                  },
                                  cursorColor: mainColor,
                                  decoration: InputDecoration(
                                      hintText: '输入...',
                                      border: InputBorder.none,
                                      filled: true,
                                      fillColor: Colors.grey.shade50),
                                ),
                              ],
                            ),
                          ),
                          actions: <Widget>[
                            CupertinoDialogAction(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child:
                                  Text('取消', style: TextStyle(color: black_99)),
                            ),
                            CupertinoDialogAction(
                              onPressed: () {
                                Navigator.pop(context);
                                editName();
                              },
                              child: Text('确定',
                                  style: TextStyle(color: mainColor)),
                            ),
                          ],
                        );
                      });
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '昵称',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(nickname,
                        style: TextStyle(
                            color: Colors.grey,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {},
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '性别',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Checkbox(
                        value: sex == 1,
                        activeColor: mainColor,
                        checkColor: black_99,
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        onChanged: (bool x) {
                          sex = 1;
                          setState(() {});
                          editName();
                        }),
                    Text(
                      '男',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                    Checkbox(
                        value: sex == 2,
                        activeColor: mainColor,
                        checkColor: black_99,
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        onChanged: (bool x) {
                          sex = 2;
                          setState(() {});
                          editName();
                        }),
                    Text(
                      '女',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  showStartDay();
                  // Navigator.of(context)
                  //     .push(MaterialPageRoute(builder: (context) {
                  //   return new ChangePhonePage();
                  // }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '生日',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(birthday == null ? "待完善" : birthday,
                        style: TextStyle(
                            color: Colors.grey,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  yaoqin == null || yaoqin == ''
                      ? Navigator.of(context)
                          .push(MaterialPageRoute(builder: (context) {
                          return new BindReferrerPage();
                        }))
                      : Navigator.of(context)
                          .push(MaterialPageRoute(builder: (context) {
                          return new ReferrerPage();
                        }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '绑定推荐人',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(yaoqin == null || yaoqin == '' ? "未绑定" : "已绑定",
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () async {
                  var result = await FlutterAlibc.loginTaoBao();
                  if (result.errorCode != "0") {
                    Toast.toast(context, msg: result.errorMessage);
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "绑定中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  bintTb(result.data.openId);
                  // print(result.toString()+"  "+result.data.open);
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '淘宝绑定',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(isBind_tb ? "已绑定" : "未绑定",
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  Clipboard.setData(ClipboardData(text: auth_code));

                  Toast.toast(context, msg: '邀请码已复制');
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '邀请码',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(auth_code,
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(DP_20), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  is_bind();
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '支付宝绑定',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(
                      '',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black45),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(0, 1, 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return new SetPayPwdPage();
                  }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '提现密码',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(
                      '',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black45),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20),
                  ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return new LoginPwdPage();
                  }));
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '登录密码',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            // Container(
            //   padding:
            //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            //   margin: EdgeInsets.fromLTRB(0, 1, 0, 0),
            //   color: Colors.white,
            //   child: new GestureDetector(
            //     onTap: () {
            //       Navigator.of(context)
            //           .push(MaterialPageRoute(builder: (context) {
            //         return new SetPayPwdPage();
            //       }));
            //     },
            //     child: new Row(
            //       children: <Widget>[
            //         Expanded(
            //           child: Text(
            //             '支付密码',
            //             style: TextStyle(
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(NORMAL_FONT_SIZE),
            //                 color: Colors.black87),
            //           ),
            //         ),
            //         Text("未设置",
            //             style: TextStyle(
            //                 color: Colors.grey,
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(SMALL_FONT_SIZE))),
            //         Icon(
            //           Icons.arrow_forward_ios,
            //           color: Colors.grey,
            //           size: 20,
            //         )
            //       ],
            //     ),
            //   ),
            // ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(0, 1, 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  if (!isBind) {
                    showDialog(
                      context: context,
                      builder: (context) => new AlertDialog(
                        title: new Text('提示'),
                        content: new Text("绑定微信需退出登录选择'微信登录'，绑定后可直接使用微信登录"),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () => Navigator.of(context).pop(false),
                            child: new Text(
                              '取消',
                              style: TextStyle(color: Colors.grey),
                            ),
                          ),
                          new FlatButton(
                            onPressed: () {
                              saveString(TOKEN, null);
                              saveString('is_Bind', null);
                              Navigator.of(context).pop();
                              Navigator.of(context).pop();
                              Navigator.of(context).pushNamed("login");

                              // if (!isWxInstall) {
                              //   Toast.toast(context, msg: "请先安装微信客户端");
                              //   return;
                              // }
                              // // print('object');
                              // _wechat.auth(
                              //   scope: <String>[WechatScope.SNSAPI_USERINFO],
                              //   state: 'auth',
                              // );
                              // Navigator.of(context).pop(false);
                            },
                            child: new Text('确定',
                                style: TextStyle(color: mainColor)),
                          ),
                        ],
                      ),
                    );
                    return;
                  }
                  showDialog(
                    context: context,
                    builder: (context) => new AlertDialog(
                      title: new Text('提示'),
                      content: new Text('确定要解除绑定微信吗'),
                      actions: <Widget>[
                        new FlatButton(
                          onPressed: () => Navigator.of(context).pop(false),
                          child: new Text(
                            '取消',
                            style: TextStyle(color: Colors.grey),
                          ),
                        ),
                        new FlatButton(
                          onPressed: () {
                            // del(index);
                            register();
                            Navigator.of(context).pop(false);
                          },
                          child: new Text('确定解绑',
                              style: TextStyle(color: mainColor)),
                        ),
                      ],
                    ),
                  );
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '微信授权绑定',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(isBind ? "已绑定" : "未绑定",
                        style: TextStyle(
                            color: Colors.grey,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  2,
                  ScreenUtil.getInstance().setHeight(DP_20),
                  2),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  print('saf');
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '消息通知',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    XlivSwitch(
                      value: this.check,
                      activeColor: mainColor,
                      unActiveColor: Colors.grey, // 激活时原点颜色
                      onChanged: (bool val) {
                        checkInform();
                      },
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(0, 1, 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  checkVersion();
                },
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '检查更新',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Text(
                      '$packageName',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black45),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              margin: EdgeInsets.fromLTRB(0, 1, 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                onTap: () {
                  print('saf');
                },
                child: new Row(
                  children: <Widget>[
                    Text(
                      '应用缓存',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_20),
                            3,
                            ScreenUtil.getInstance().setHeight(DP_20),
                            0),
                        child: Text(
                          '$_cacheSizeStr',
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE)),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        //此处展示加载loading
                        showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (_) {
                              return new NetLoadingDialog(
                                loadingText: "清理中...",
                                bgColor: Color.fromARGB(255, 0, 0, 0),
                                requestCallBack: _clearCache(context),
                                outsideDismiss: false,
                              );
                            });
                      },
                      child: Container(
                        padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                        decoration: new BoxDecoration(
                            border: Border.all(color: mainColor, width: 1),
                            borderRadius: BorderRadius.circular(10.0)),
                        child: Text(
                          '清理缓存',
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            Row(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return new ArticleDetailPage(
                        article_id: "1",
                      );
                    }));
                  },
                  child: Text(
                    '《用户协议》',
                    style: TextStyle(color: Colors.red),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return new ArticleDetailPage(
                        article_id: "8",
                      );
                    }));
                  },
                  child: Text(
                    '《隐私政策》',
                    style: TextStyle(color: Colors.red),
                  ),
                ),
              ],
            ),
            new Container(
              width: double.infinity,
              height: ScreenUtil.getInstance().setHeight(DP_80),
              margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(DP_50)),
              decoration: new BoxDecoration(
                  color: Colors.red, borderRadius: BorderRadius.circular(5.0)),
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.all(0.0),
                  child: new Text(
                    "退出登录",
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  saveString(TOKEN, null);
                  saveString(TOKEN, null);
                  saveString("name", '');
                  saveString("pwd", '');
                  saveString('is_Bind', null);
                  Navigator.of(context).pop();
                  Navigator.of(context).pushNamed("login");
                },
              ),
            ),
            // GestureDetector(
            //   child: Text(
            //     '注销账号',
            //     style: TextStyle(
            //         fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
            //         color: mainColor),
            //   ),
            //   onTap: () {
            //     showDialog(
            //       context: context,
            //       builder: (context) => new AlertDialog(
            //         title: new Text('提示'),
            //         content: new Text('确定注销账号吗，注销后账号不可用'),
            //         actions: <Widget>[
            //           new FlatButton(
            //             onPressed: () => Navigator.of(context).pop(false),
            //             child: new Text(
            //               '取消',
            //               style: TextStyle(color: Colors.grey),
            //             ),
            //           ),
            //           new FlatButton(
            //             onPressed: () {
            //               Navigator.of(context).pop(false);
            //               showDialog(
            //                   context: context,
            //                   barrierDismissible: false,
            //                   builder: (_) {
            //                     return new NetLoadingDialog(
            //                       loadingText: "注销中...",
            //                       bgColor: Color.fromARGB(255, 0, 0, 0),
            //                       requestCallBack: null,
            //                       outsideDismiss: false,
            //                     );
            //                   });
            //               zhuxiao();
            //             },
            //             child: new Text('确定注销',
            //                 style: TextStyle(color: mainColor)),
            //           ),
            //         ],
            //       ),
            //     );
            //   },
            // ),
            Container(height: 20)
          ],
        ),
      )),
    );
  }

  is_bind() async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.BandingAli, data: data);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      saveString('is_Bind', userMap['data']['is_banding']);
      userMap['data']['is_banding'] == 'Y'
          ? Navigator.of(context)
              .push(new MaterialPageRoute(builder: (context) {
              return new BindZfbPage(type: '');
            }))
          : Navigator.of(context)
              .push(new MaterialPageRoute(builder: (context) {
              return new BindZfbPage(type: '1');
            }));
    }
  }

  is_bindTJ() async {
    //获取推荐人信息
    Map map = new Map();
    map['token'] = token;
    // map['sign_type'] = SignType.FREEZE_ACCOUNT;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response = await HttpUtil()
        .post(Api.BaseUrl + '/app.php?c=User&a=getRMsg', data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(userMap);
    if (code == 1 && mounted) {
      setState(() {
        yaoqin = userMap['data']['referrerMsg']['phone'].toString();
      });
    } else {}
  }

  checkWx() async {
    // Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    // Response<String> response =
    //     await HttpUtil().post(Api.VERSION_CHECK, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // if (userMap['code'] == 1 && mounted) {
    isWxInstall = await _wechat.isWechatInstalled();
    setState(() {});
    // }
  }

  void _listenAuth(WechatAuthResp resp) {
    _authResp = resp;
    if (_authResp != null &&
        _authResp.errorCode == WechatSdkResp.ERRORCODE_SUCCESS) {
      _wechat
          .getAccessTokenUnionID(
        appId: WX_APPID,
        appSecret: WX_APP_SECRET,
        code: _authResp.code,
      )
          .then((WechatAccessTokenResp accessTokenResp) {
        if (accessTokenResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
          _wechat
              .getUserInfoUnionID(
            openId: accessTokenResp.openid,
            accessToken: accessTokenResp.accessToken,
          )
              .then((WechatUserInfoResp userInfoResp) {
            if (userInfoResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return new NetLoadingDialog(
                      loadingText: "检测中...",
                      bgColor: Color.fromARGB(255, 0, 0, 0),
                      requestCallBack: null,
                      outsideDismiss: false,
                    );
                  });
              checkIsWxBind(userInfoResp);
              // _showTips(
              //     '用户信息', '${userInfoResp.nickname} - ${userInfoResp.sex}');
            }
          });
        }
      });
    } else {
      Toast.toast(context, msg: "微信登录失败");
    }
  }

  checkIsWxBind(WechatUserInfoResp resp) async {
    Map map = new Map();
    map['openid'] = resp.openid;
    map['type'] = "wx";
    // map['sign_type'] = SignType.CHECK_WX_IS_BIND;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.CheckRegisterOauthUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Toast.toast(context, msg: msg);
    if (msg == '成功，已授权' && mounted) {
      // Toast.toast(context, msg: "登录成功");
      // saveString(TOKEN, userMap['data']['token']);
      // saveString(UID, userMap['data']['uid'].toString());
      // saveString(GROUP_ID, userMap['data']['group_id'].toString());
      // APPLIC.eventBus.fire(LoginEvent());
      // Navigator.of(context).pop();
    } else {
      Toast.toast(context, msg: msg);
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new BindWxPage(
          type: "wx",
          openId: resp.openid,
          nickname: resp.nickname,
          avatar: resp.headimgurl,
          sex: resp.sex.toString(),
        );
      }));
    }
  }

  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int versionCode = int.parse(packageInfo.version.replaceAll(".", ""));
    Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    Response<String> response =
        await HttpUtil().post(Api.GetVersionUrl, data: map);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      if (Platform.isAndroid) {
        int service = int.parse(
            userMap['data']['version_android'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否下载更新'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    downApk(userMap['data']['down_android']);
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即下载', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        } else {
          // Fluttertoast.showToast(msg: "已是最新版本");
          Toast.toast(context, msg: "已是最新版本");
        }
      } else {
        int service = int.parse(
            userMap['data']['version_ios'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否前去下载'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    final url =
                        "https://itunes.apple.com/cn/app/id1380512641"; // id 后面的数字换成自己的应用 id 就行了
                    if (await canLaunch(url)) {
                      await launch(url, forceSafariVC: false);
                    } else {
                      throw 'Could not launch $url';
                    }
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即前往', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        } else {
          Toast.toast(context, msg: "已是最新版本");
        }
      }
    }
  }

  downApk(String url) async {
    Directory dic;
    dic = await getExternalStorageDirectory();
    Response response;
    File file = File(dic.path +
        "/" +
        DateTime.now().millisecondsSinceEpoch.toString() +
        ".apk");
    if (!file.existsSync()) {
      file.createSync();
    }
    try {
      response = await new Dio().download(url, file.path,
          onReceiveProgress: (int count, int total) {
        //进度
        _showNotification(
            (count * 100 / total).toString().substring(0, 5) + '%');
      });
      if (response.statusCode == 200) {
        _installApk(file.path);
        flutterLocalNotificationsPlugin.cancelAll();
        // Fluttertoast.showToast(msg: '下载成功');
      }
      // print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      // Fluttertoast.showToast(msg: '下载出错');
      Toast.toast(context, msg: "下载出错");
      // print('downloadFile error---------$e');
    }
  }

  Future _showNotification(String str) async {
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        '1', 'xiongmao', 'xinogmao',
        importance: Importance.Max, priority: Priority.High);
    //IOS的通知配置
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        0, '更新服务正在运行', '已下载$str', platformChannelSpecifics,
        payload: 'complete');
  }

  // 调用android代码安装apk
  void _installApk(String path) {
    const platform = MethodChannel("com.dmooo.panda/update");
    try {
      // 调用app地址
      platform.invokeMethod(
          'install', {"bundleId": "com.dmooo.panda", "path": path});
    } on PlatformException catch (_) {}
  }

  Future<bool> _clearCache(BuildContext context) async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      await delDir(tempDir);

      Toast.toast(context, msg: "清除缓存成功");

      // Fluttertoast.showToast(
      //     msg: "清除缓存成功",
      //     toastLength: Toast.LENGTH_SHORT,
      //     gravity: ToastGravity.CENTER,
      //     timeInSecForIos: 1,
      //     backgroundColor: Colors.black,
      //     textColor: Colors.white);
    } catch (e) {
      Toast.toast(context, msg: "清除缓存失败");
      // Fluttertoast.showToast(
      //     msg: "清除缓存失败",
      //     toastLength: Toast.LENGTH_SHORT,
      //     gravity: ToastGravity.CENTER,
      //     timeInSecForIos: 1,
      //     backgroundColor: Colors.black,
      //     textColor: Colors.white);
    } finally {
      //此处隐藏加载loading
    }
  }

  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }

  ///加载缓存
  Future<Null> loadCache() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    packageName = packageInfo.version;
    setState(() {});
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路���
        print(file.path);
      });*/
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSizeStr = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }

  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

  ///格式化文件大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  Future<void> selHead() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
      //  error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList == null || resultList.length <= 0) {
      return;
    }
    // upImg = resultList[0];
    // upFilePath = await resultList[0].filePath;
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new NetLoadingDialog(
            loadingText: "上传中...",
            bgColor: Color.fromARGB(255, 0, 0, 0),
            requestCallBack: null,
            outsideDismiss: false,
          );
        });

    upHead(resultList[0]);
    setState(() {});
  }

  // Future<List<int>> testComporessList(List<int> list) async {
  //   var result = await FlutterImageCompress.compressWithList(
  //     list,
  //     minHeight: 1920,
  //     minWidth: 1080,
  //     quality: 96,
  //     rotate: 0,
  //   );
  //   print(list.length);
  //   print(result.length);
  //   return result;
  // }
  void showStartDay() {
    DatePicker.showDatePicker(context,
        showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
      setState(() {
        birthday = DateUtils.instance.getFormartData(
            timeSamp: date.millisecondsSinceEpoch, format: "yyyy-MM-dd");
        editName();
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  editName() async {
    Map map = new Map();
    map['nickname'] = nickname == null ? "" : nickname;
    map['sex'] = sex == null ? "" : sex.toString();
    map['birthday'] = birthday == null ? "" : birthday;
    map['token'] = token;
    print(map);
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    // map['sign_type'] = SignType.EDIT_USER_MSG;
    Response<String> response =
        await HttpUtil().post(Api.EditUserMsgUrl, data: fromData);
    Map userMap = json.decode(response.data);
    // Navigator.of(context).pop(1);
    // Fluttertoast.showToast(msg: userMap['msg']);
    Toast.toast(context, msg: userMap['msg']);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _getUserMsg(token);
      });
    }
  }

  upHead(Asset img) async {
    ByteData byteData = await img.getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    MultipartFile file = MultipartFile.fromBytes(imageData, filename: img.name);
    Map map = new Map();
    map['token'] = token;
    map['user_avatar'] = file;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.EditUserAvatarUrl, data: data);
    Map userMap = json.decode(response.data);
    print('头像');
    print(response);
    print(userMap);
    Navigator.of(context).pop(1);
    // Fluttertoast.showToast(msg: userMap['msg']);
    Toast.toast(context, msg: userMap['msg']);
    if (userMap['code'] == 1 && mounted) {
      // APPLIC.userInfoMap=userMap['data'];
      // APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    }

    // ByteData byteData = await img.getByteData();
    // List<int> imageData = byteData.buffer.asUint8List();
    // MultipartFile file = MultipartFile.fromBytes(imageData, filename: img.name);
    // Map map = new Map();
    // map['dir'] = "work/";
    // map['file'] = file;
    // map['file_name'] =img.name;
    // FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    // Response<String> response =
    //     await HttpUtil().post('http://4.dmooo.net/index.php/wap/Qn/upload', data: data);
    // Map userMap = json.decode(response.data);
    // print('头像');
    // print(response);
    // print(userMap);
    // Navigator.of(context).pop(1);
    // // Fluttertoast.showToast(msg: userMap['msg']);
    // Toast.toast(context, msg: userMap['msg']);
    // if (userMap['code'] == 1 && mounted) {
    //   // APPLIC.userInfoMap=userMap['data'];
    //   // APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    // }
  }

  register() async {
    // showDialog(
    //     context: context,
    //     barrierDismissible: false,
    //     builder: (_) {
    //       return new NetLoadingDialog(
    //         loadingText: "解绑中...",
    //         bgColor: Color.fromARGB(255, 0, 0, 0),
    //         requestCallBack: null,
    //         outsideDismiss: false,
    //       );
    //     });
    // Map map = new Map();
    // map['token'] = token;
    // // map['sign_type'] = SignType.UNBIND_WX;
    // // if (inviteController.text.length > 10) {
    // //   map['referrer_phone'] = inviteController.text;
    // // } else if (inviteController.text.length > 4) {
    // //   map['auth_code'] = inviteController.text;
    // // }
    // Response<String> response =
    //     await HttpUtil().post(Api.UNBIND_WX, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // int code = userMap["code"];
    // String msg = userMap["msg"];
    // Navigator.of(context).pop(1);
    // Fluttertoast.showToast(msg: msg);
    // if (code == 1 && mounted) {
    //   isBind = false;
    //   setState(() {});
    // }
  }
}
